package com.ytt.core.api.security;

import org.springframework.security.crypto.password.PasswordEncoder;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;

/**
 * Md5PasswordEncoder
 *
 * @author chenwen
 * @date 2019/9/16 09:12
 */
public class Md5PasswordEncoder implements PasswordEncoder {
    private static String md5(String data) {
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.update(data.getBytes(StandardCharsets.UTF_8));
            byte[] md5Array = md5.digest();
            return bytesToHex(md5Array);
        } catch (Exception e) {
            return "";
        }
    }

    private static String bytesToHex(byte[] byteArray) {
        char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
        char[] resultCharArray = new char[byteArray.length * 2];
        int index = 0;
        for (byte b : byteArray) {
            resultCharArray[index++] = hexDigits[b >>> 4 & 0xf];
            resultCharArray[index++] = hexDigits[b & 0xf];
        }
        return new String(resultCharArray);
    }

    @Override
    public String encode(CharSequence rawPassword) {
        return md5(rawPassword.toString());
    }

    @Override
    public boolean matches(CharSequence rawPassword, String encodedPassword) {
        String md5 = md5(rawPassword.toString());
        return encodedPassword.equalsIgnoreCase(md5);
    }
}
